package com.fastjrun.bms.service.impl;

import com.fastjrun.common.ServiceException;
import com.fastjrun.dto.PageResult;
import com.fastjrun.bms.common.CodeMsgConstants;
import com.fastjrun.bms.dao.SysUserDao;
import com.fastjrun.bms.dto.ChangePwdDTO;
import com.fastjrun.bms.dto.UserDTO;
import com.fastjrun.bms.dto.UserQueryDTO;
import com.fastjrun.bms.entity.SysUser;
import com.fastjrun.bms.entity.SysUserExample;
import com.fastjrun.bms.helper.DTOToEntifyConverter;
import com.fastjrun.bms.helper.EntityToVOConverter;
import com.fastjrun.bms.service.BaseDemoService;
import com.fastjrun.bms.service.SysUserManagerService;
import com.fastjrun.bms.vo.TotalVO;
import com.fastjrun.bms.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 * @author cuiyingfeng @Copyright 2021 快嘉. All rights reserved.
 */
@Service("sysUserManagerService")
public class SysUserManagerServiceImpl extends BaseDemoService implements SysUserManagerService {

  @Autowired SysUserDao sysUserDao;

  @Autowired PasswordEncoder passwordEncoder;

  /** 条件分页查询用户列表 */
  @Override
  public PageResult<UserVO> search(UserQueryDTO requestBody) {
    PageResult<UserVO> response = new PageResult();


    String mobile = requestBody.getMobile();
    String userName = requestBody.getUsername();
    Integer current = requestBody.getCurrent();
    Integer size = requestBody.getSize();

    SysUserExample sysUserExample = new SysUserExample();
    SysUserExample.Criteria criteria = sysUserExample.createCriteria();

    if (current == null) {
      current = PAGE_CURRENT;
    }
    if (size == null) {
      size = PAGE_SIZE;
    }

    if (mobile != null && !mobile.equals("")) {
      criteria.andMobileEqualTo(mobile);
    }

    if (userName != null && !userName.equals("")) {
      if (criteria.getCriteria().size() > 0) {
        sysUserExample.or().andUsernameLike("%" + userName + "%");
      } else {
        criteria.andUsernameLike("%" + userName + "%");
      }
    }

    PageHelper.startPage(current, size, true);

    PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserDao.selectByExample(sysUserExample));

    List<UserVO> list =
        pageInfo.getList().stream().map(EntityToVOConverter::convert).collect(Collectors.toList());

    response.setRows(list);
    response.setCurrPage(current);
    response.setPageSize(size);
    response.setTotalPage(pageInfo.getPages());
    response.setTotal((int) pageInfo.getTotal());
    return response;
  }

  /** 查询用户信息 */
  @Override
  public UserVO getById(Long id) {
    SysUser sysUser = sysUserDao.selectByPrimaryKey(id);
    return EntityToVOConverter.convert(sysUser);
  }

  /** 新增用户 */
  @Override
  public void add(UserDTO requestBody) {
    SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
    // 默认用户密码就是用户名
    sysUser.setPassword(requestBody.getUsername());
    Date currentDate = new Date(System.currentTimeMillis());
    sysUser.setCreateDate(currentDate);
    sysUser.setUpdateDate(currentDate);
    sysUser.setIsEnabled(1);
    sysUserDao.insert(sysUser);
  }

  /** 修改用户 */
  @Override
  public void save(UserDTO requestBody) {
    SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
    Date currentDate = new Date(System.currentTimeMillis());
    sysUser.setUpdateDate(currentDate);
    sysUserDao.updateByPrimaryKeySelective(sysUser);
  }

  /** 删除用户信息 */
  @Override
  public void deleteById(Long id) {
    sysUserDao.deleteByPrimaryKey(id);
  }

  /** 修改新密码 */
  @Override
  public void password(ChangePwdDTO requestBody) {
    Long userId = requestBody.getUserId();
    String newPassword = requestBody.getNewPassword();
    String repPassword = requestBody.getRepPassword();
    if (!newPassword.equals(repPassword)) {
      throw new ServiceException(
          CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003,
          this.serviceMessageSource.getMessage(
              CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003, null, null));
    }
    SysUser record = new SysUser();
    record.setId(userId);
    record.setPassword(passwordEncoder.encode(newPassword));
    Date currentDate = new Date(System.currentTimeMillis());
    record.setUpdateDate(currentDate);
    sysUserDao.updateByPrimaryKeySelective(record);
  }

  @Override
  public TotalVO total() {
    TotalVO totalVO = new TotalVO();
    SysUserExample sysUserExample = new SysUserExample();
    totalVO.setTotal(sysUserDao.countByExample(sysUserExample));
    return totalVO;
  }
}
